#define JMBC_INSIDE
#include "tlString.h"
#include "id.h"
#include "tlGroup.h"
#include "elError.h"
#include <string.h>
#include <stdio.h>

// Context

#define STORE ID_SMALL_STORE

static TLString *store[STORE];

void
tlStringCreateContext(void)
{
	idClearStore(TLString, STORE, store);
}

// Generation / Deletion

static
void
Init(TLString *string)
{
}

static
void
Term(TLString *string)
{
}

void
tlGenStrings(unsigned int n, unsigned int *strings)
{
	idGenObjects(TLString, STORE, store, Init, n, strings);
}

void
tlDeleteStrings(unsigned int n, unsigned int *strings)
{
	idDeleteObjects(store, Term, n, strings);
}

// Load / Unload

void
tlStringLoad(unsigned int id, const wchar_t *data)
{
	TLString *string;

	string = store[id];

	string->data = wcsdup(data);
	string->length = wcslen(data);
}

void
tlStringUnload(unsigned int id)
{
	TLString *string;

	string = store[id];

	free(string->data);
}

void
tlStringsUnload(unsigned int n, unsigned int *strings)
{
	unsigned int i;

	for(i = 0; i < n; i++)
		tlStringUnload(strings[i]);
}

// Query

const wchar_t *
tlStringData(unsigned int id)
{
	TLString *string;

	string = store[id];

	return string->data;
}

unsigned int
tlStringLength(unsigned int id)
{
	TLString *string;

	string = store[id];

	return string->length;
}

// Operation

void
tlStringConcat(unsigned int id, unsigned int n, unsigned int *strings)
{
	TLString *string;
	unsigned int i;

	string = store[id];

	for(string->length = 1, i = 0; i < n; string->length += tlStringLength(strings[i]), i++);
	string->data = malloc(string->length * sizeof(wchar_t));
	for(wcscpy(string->data, tlStringData(strings[0])), i = 1; i < n; wcscat(string->data, tlStringData(strings[i])), i++);
}

void
tlStringConcatPath(unsigned int id, unsigned int n, unsigned int *strings)
{
	TLString *string;
	unsigned int i;

	string = store[id];

	for(string->length = n, i = 0; i < n; string->length += tlStringLength(strings[i]), i++);
	string->data = malloc(string->length * sizeof(wchar_t));
	for(wcscpy(string->data, tlStringData(strings[0])), i = 1; i < n; wcscat(string->data, TL_STRING_PATH_SEPARATOR), wcscat(string->data, tlStringData(strings[i])), i++);
}

void
tlStringLoadC(unsigned int id, const char *data)
{
	wchar_t tmp[256];

	mbstowcs(tmp, data, 256);
	tlStringLoad(id, tmp);
}
